package com.jinlejia.erp.ui.new_house.house;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.poi.PoiSortType;
import com.jinlejia.erp.R;
import com.weight.CustomToast;

import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

public class HousePoiSearchActivity extends AppCompatActivity implements View.OnClickListener, OnGetPoiSearchResultListener {

    public static double x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    private PoiSearch mPoiSearch = null;
    private BaiduMap mBaiduMap = null;
    PoiNearbySearchOption place;
    private SwitchMapDialog dialog;

    //117.192601,39.092714
    LatLng center;
    int radius = 5000;
    private String city;
    private String Address;
    private String Title;
    private static String mlat;
    private static String mlng;
    private int markID;
    private InfoWindow infoWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_house_poi_search);
        if(!TextUtils.isEmpty(getIntent().getStringExtra("lat"))) {
            center = new LatLng(Double.parseDouble(getIntent().getStringExtra("lat")), Double.parseDouble(getIntent().getStringExtra("lng")));
        }else{
            center = new LatLng(0,0);
        }
        city = getIntent().getStringExtra("city");
        Address = getIntent().getStringExtra("address");
        Title = getIntent().getStringExtra("title");
        bd09_To_Gcj02(Double.parseDouble(getIntent().getStringExtra("lat")), Double.parseDouble(getIntent().getStringExtra("lng")));
        initView();
    }

    private void initView() {
        dialog = new SwitchMapDialog(this);
        ImageView back = findViewById(R.id.id_back);
        RadioGroup radioGroup = findViewById(R.id.id_map_bottom_group);
        // 初始化搜索模块，注册搜索事件监听
        mPoiSearch = PoiSearch.newInstance();
        mPoiSearch.setOnGetPoiSearchResultListener(this);
        place = new PoiNearbySearchOption();
        place.sortType(PoiSortType.distance_from_near_to_far).location(center).radius(2000).pageNum(0);

        mBaiduMap = ((BaiduSupportFragment) (getSupportFragmentManager()
                .findFragmentById(R.id.map))).getBaiduMap();
        MyLocationData locData = new MyLocationData.Builder()
                .accuracy(1.0f)
                // 此处设置开发者获取到的方向信息，顺时针0-360
                .direction(100).latitude(center.latitude)
                .longitude(center.longitude).build();
        mBaiduMap.setMyLocationData(locData);
        MapStatus.Builder builder = new MapStatus.Builder();
        builder.target(center).zoom(15.0f);
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));

        mBaiduMap.getUiSettings().setAllGesturesEnabled(true);

        // 在地图上添加marker，并显示
        mBaiduMap.addOverlay(getOptions(center,R.mipmap.details_map,"锁定目标"));

        mBaiduMap.setOnMarkerClickListener(marker -> {

            if (marker.getTitle().equals("锁定目标")){
                View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_map_icon, null);
                TextView mtitle = view.findViewById(R.id.location_title);
                TextView maddress = view.findViewById(R.id.location_address);
                mtitle.setText(getIntent().getStringExtra("title"));
                maddress.setText(getIntent().getStringExtra("address"));
                final BitmapDescriptor markerIcon = BitmapDescriptorFactory.fromBitmap(getViewBitmap(view));
                infoWindow = new InfoWindow(markerIcon,marker.getPosition(),-100,itemsOnClick);
            }else {
                View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_out_map_icon, null);
                TextView mtitle = view.findViewById(R.id.location_title);
                infoWindow = new InfoWindow(view,marker.getPosition(),-100);
                mtitle.setText(marker.getTitle());
            }
            mBaiduMap.showInfoWindow(infoWindow);
            return false;
        });
        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                mBaiduMap.hideInfoWindow();
            }

            @Override
            public void onMapPoiClick(MapPoi mapPoi) {
            }
        });
        back.setOnClickListener(this);
        radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId){
                case R.id.id_map_bus:
                    //公交
                    place.keyword("公交");
                    markID = R.mipmap.map_position_bus;
                    break;
                case R.id.id_map_metro:
                    //地铁
                    place.keyword("地铁");
                    markID = R.mipmap.map_position_subway;
                    break;
                case R.id.id_map_school:
                    //
                    place.keyword("学校");
                    markID = R.mipmap.map_position_school;
                    break;
                case R.id.id_map_cater:
                    //
                    place.keyword("餐饮");
                    markID = R.mipmap.map_position_food;
                    break;
                case R.id.id_map_hospital:
                    //
                    place.keyword("医院");
                    markID = R.mipmap.map_position_hospital;
                    break;
                case R.id.id_map_bank:
                    //
                    place.keyword("银行");
                    markID = R.mipmap.map_position_bank;
                    break;
                case R.id.id_map_shopping:
                    //
                    place.keyword("购物");
                    markID = R.mipmap.map_position_shopping;
                    break;
                default:
                    break;
            }
            mPoiSearch.searchNearby(place);
        });

        dialog.setConfirmListener(new SwitchMapDialog.OnConfirmListener() {
            Intent intent = null;
            @Override
            public void baidu() {
                if(isAvilible(HousePoiSearchActivity.this,"com.baidu.BaiduMap")){//传入指定应用包名
                    try {
//                        intent = Intent.getIntent("intent://map/direction?origin=latlng:34.264642646862,108.95108518068|name:我家&destination=大雁塔&mode=driving®ion=西安&src=yourCompanyName|yourAppName#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
                        intent = Intent.getIntent("intent://map/direction?" +
                                //"origin=latlng:"+"34.264642646862,108.95108518068&" +   //起点  此处不传值默认选择当前位置
                                "destination=latlng:"+getIntent().getStringExtra("lat")+","+getIntent().getStringExtra("lng")+"|name:我的目的地"+        //终点
                                "&mode=driving&" +          //导航路线方式
                                "region=" + city +           //
                                "&src=InHome#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
                        HousePoiSearchActivity.this.startActivity(intent); //启动调用
                    } catch (URISyntaxException e) {
                        Log.e("intent", e.getMessage());
                    }
//                }else{//未安装
//                    //market为路径，id为包名
//                    //显示手机上所有的market商店
//                    Toast.makeText(HousePoiSearchActivity.this, "您尚未安装百度地图", Toast.LENGTH_LONG).show();
//                    Uri uri = Uri.parse("market://details?id=com.baidu.BaiduMap");
//                    intent = new Intent(Intent.ACTION_VIEW, uri);
//                    HousePoiSearchActivity.this.startActivity(intent);
                }
            }

            @Override
            public void gaode() {
                if (isAvilible(HousePoiSearchActivity.this, "com.autonavi.minimap")) {
                    try{
                        intent = Intent.getIntent("androidamap://navi?sourceApplication=InHome&poiname=我的目的地&lat="+ mlat+"&lon="+mlng+"&dev=0");
                        HousePoiSearchActivity.this.startActivity(intent);
                    } catch (URISyntaxException e)
                    {e.printStackTrace(); }
//                }else{
//                    Toast.makeText(HousePoiSearchActivity.this, "您尚未安装高德地图", Toast.LENGTH_LONG).show();
//                    Uri uri = Uri.parse("market://details?id=com.autonavi.minimap");
//                    intent = new Intent(Intent.ACTION_VIEW, uri);
//                    HousePoiSearchActivity.this.startActivity(intent);
                }
            }

            @Override
            public void cancel() {
                dialog.dismiss();
            }
        });

    }

    /**
     * 获取marker
     * @param id
     * @return
     */
    public OverlayOptions getOptions(LatLng latLng, int id, String title){
        return   new MarkerOptions()
                .position(latLng)// 设置marker的位置
                .title(title)
                .icon(BitmapDescriptorFactory.fromResource(id))// 设置marker的图标
                .zIndex(9)// 設置marker的所在層級
                .draggable(true);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.id_back:
                finish();
                break;
            default:
                break;
        }
    }

    /**
     * 获取POI搜索结果，包括searchInCity，searchNearby，searchInBound返回的搜索结果
     *
     * @param poiResult
     */
    public void onGetPoiResult(PoiResult poiResult) {
        List<PoiInfo> allPoi = new ArrayList<>();
        //搜索到内容   NO_ERROR
        if (poiResult.error == SearchResult.ERRORNO.NO_ERROR) {
            mBaiduMap.clear();
            allPoi = poiResult.getAllPoi();
            mBaiduMap.addOverlay(getOptions(center,R.mipmap.details_map,"锁定目标"));
            for (int i = 0, j = allPoi.size(); i < j; i++) {
                mBaiduMap.addOverlay(getOptions(allPoi.get(i).location,markID,allPoi.get(i).name));
            }
        } else {
            Toast.makeText(HousePoiSearchActivity.this,"没有搜索结果", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {

    }

    @Override
    public void onGetPoiDetailResult(PoiDetailSearchResult poiDetailSearchResult) {

    }

    @Override
    public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

    }

    @Override
    protected void onDestroy() {
        mPoiSearch.destroy();

        super.onDestroy();
    }

    /**
     * 检查手机上是否安装了指定的软件
     * @param context
     * @param packageName：应用包名
     * @return
     */
    public static boolean isAvilible(Context context, String packageName){
        //获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        //获取所有已安装程序的包信息
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        //用于存储所有已安装程序的包名
        List<String> packageNames = new ArrayList<String>();
        //从pinfo中将包名字逐一取出，压入pName list中
        if(packageInfos != null){
            for(int i = 0; i < packageInfos.size(); i++){
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        //判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
        return packageNames.contains(packageName);
    }

    private Bitmap getViewBitmap(View addViewContent) {

        addViewContent.setDrawingCacheEnabled(true);

        addViewContent.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        addViewContent.layout(0, 0, addViewContent.getMeasuredWidth(), addViewContent.getMeasuredHeight());

        addViewContent.buildDrawingCache();
        Bitmap cacheBitmap = addViewContent.getDrawingCache();
        Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);

        return bitmap;
    }

    /**
     * * 火星坐标系 (GCJ-02) 与百度坐标系 (BD-09) 的转换算法 * * 将 BD-09 坐标转换成GCJ-02 坐标 * * @param
     * bd_lat * @param bd_lon * @return
     */
    public static void bd09_To_Gcj02(double lat, double lon) {
        double x = lon - 0.0065, y = lat - 0.006;
        double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
        String tempLon = String.valueOf(z * Math.cos(theta));
        String tempLat = String.valueOf(z * Math.sin(theta));
        mlat = tempLat;
        mlng = tempLon;
    }

    private InfoWindow.OnInfoWindowClickListener itemsOnClick = new InfoWindow.OnInfoWindowClickListener() {
        @Override
        public void onInfoWindowClick() {
            mBaiduMap.hideInfoWindow();
            Intent intent = null;
            try {
                if (isAvilible(HousePoiSearchActivity.this,"com.baidu.BaiduMap") && isAvilible(HousePoiSearchActivity.this, "com.autonavi.minimap")){
                    dialog.show();
                }else if (isAvilible(HousePoiSearchActivity.this,"com.baidu.BaiduMap")){
//                        intent = Intent.getIntent("intent://map/direction?origin=latlng:34.264642646862,108.95108518068|name:我家&destination=大雁塔&mode=driving®ion=西安&src=yourCompanyName|yourAppName#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
                    intent = Intent.getIntent("intent://map/direction?" +
                            //"origin=latlng:"+"34.264642646862,108.95108518068&" +   //起点  此处不传值默认选择当前位置
                            "destination=latlng:"+getIntent().getStringExtra("lat")+","+getIntent().getStringExtra("lng")+"|name:我的目的地"+        //终点
                            "&mode=driving&" +          //导航路线方式
                            "region=" + city +           //
                            "&src=InHome#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");

                }else if (isAvilible(HousePoiSearchActivity.this, "com.autonavi.minimap")){

                    intent = Intent.getIntent("androidamap://navi?sourceApplication=InHome&poiname=我的目的地&lat="+mlat+"&lon="+mlng+"&dev=0");

                }else {
                    CustomToast.showToast(HousePoiSearchActivity.this, "您尚未安装百度地图或高德地图",2000);
                    Uri uri = Uri.parse("market://details?id=com.baidu.BaiduMap");
                    intent = new Intent(Intent.ACTION_VIEW, uri);
                }
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
            if (null != intent){
                HousePoiSearchActivity.this.startActivity(intent); //启动调用
            }
        }
    };
}
